<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2017/3/22
 * Time: 10:22
 */

namespace Admin\Controller;

use Admin\Controller\Tencentyun\ImageV2;
use Common\Controller\AdminbaseController;
use Common\Model\NewsModel;
use Think\Model;

class PeopleManagementController extends AdminbaseController
{
    private $status;
    private $admin_id;
    private $page_count;
    private $people_model;
    private $company_model;
    private $manage_company;
    private $head_company_id;
    private $sys_admin_menu_model;

    public function __construct()
    {
        parent::__construct();
        $this->status = 1;
        $this->admin_id = session('ADMIN_ID');
        $this->page_count = 20;
        $this->people_model = M('vrnews1.personnel');
        $this->company_model = M('vrnews1.company');
        $this->head_company_id = 1;
        $this->sys_admin_menu_model = M('vradmin1.sys_menu_admin');
        $menu_id = M('vradmin1.sys_menu')->where(array('name'=>'员工管理'))->getField('menu_id');
        if($this->admin_id != 1 && I('company_id', 0, 'intval') == 0){
            $this->manage_company = $this->sys_admin_menu_model->alias('s')->field('c.*')->join('vrnews1.company c ON s.company_id = c.company_id ')->where(array('s.admin_id'=>$this->admin_id, 's.company_id'=>array('neq', 0), 's.menu_id'=>$menu_id))->find();
            $this->assign('admin_type', 2);
            if(!$this->manage_company['company_id']){exit(json_encode(array('code'=>110, 'msg'=>'error')));}
            $this->assign('company_id', $this->manage_company['company_id']);
        }elseif($this->admin_id == 1 && I('company_id', 0, 'intval')){
            $this->manage_company = $this->company_model->where(array('company_id'=>I('company_id', 0, 'intval')))->find();
            $this->assign('admin_type', 1);
            $this->assign('company_id', I('company_id', 0, 'intval'));
        }elseif($this->admin_id == 1 && !I('company_id', 0, 'intval')){
            $this->manage_company = $this->sys_admin_menu_model->alias('s')->field('c.*')->join('vrnews1.company c ON s.company_id = c.company_id ')->where(array('s.admin_id'=>$this->admin_id, 's.company_id'=>array('neq', 0), 's.menu_id'=>$menu_id))->find();
            $this->assign('admin_type', 1);
            $this->assign('company_id', 0);
        }

        $this->assign('company_info', $this->manage_company);
    }

    public function index(){
        $on_where = 'c.status='.$this->status;

        if($this->admin_id != 1){
            //普通管理员
            //$manage_company = $this->sys_admin_menu_model->alias('s')->field('c.*')->join('vrnews1.company c ON s.company_id = c.company_id ')->where(array('s.admin_id'=>$this->admin_id, 's.company_id'=>array('neq', 0)))->find();
            $company_id = $this->manage_company['company_id'] ? $this->manage_company['company_id'] : I('company_id', 0, 'intval');
            $on_where .= " AND c.company_id=$company_id ";
        }else{
            $company_id = I('company_id', 0, 'intval');
        }

        $people_name = I('people_name', '', 'trim');
        $company_name = I('company_name', '', 'trim');
        if($company_id){
            $on_where .= ' AND p.company_id='.$company_id;
        }
        if($people_name){
            $on_where .= " AND p.name LIKE '%$people_name%'";
        }
        if($company_name){
            $on_where .= " AND c.name LIKE '%$company_name%'";
        }

        $on_company_people_count = $this->company_model->alias('c')->join('RIGHT JOIN vrnews1.personnel p ON c.company_id=p.company_id')->where($on_where)->count();
        $page = $this->page($on_company_people_count, $this->page_count);

        $people_list = $this->company_model
            ->alias('c')
            ->field('p.*, c.name as company_name')
            ->join('RIGHT JOIN vrnews1.personnel p ON c.company_id=p.company_id')
            ->where($on_where)
            ->order('p.create_time DESC')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();

        $this->assign('people_count', $on_company_people_count);
        $this->assign('people_list', $people_list);

        $this->assign('people_name', $people_name);
        $this->assign('company_name', $company_name);

        $this->assign('company_id', $company_id);

        $this->assign('page', $page->show('Admin'));
        $this->display();
    }

    public function addPeople(){
        if(IS_POST){
            if(!I('people_name', 0, 'trim')) $this->error('请填写员工姓名');
            if(!I('email', 0, 'trim')) $this->error('请填写员工邮箱');
            if(!I('id_card', 0, 'trim')) $this->error('请填写身份证号');
            $photo = I("photo");
            $cover_img = I("cover");
            if(!trim($photo) && !$cover_img){
                $this->error('请上传员工照片');
            }
            if(trim($photo)){
                $photo_arr = explode(',', $photo);
                $image_str 	  = base64_decode($photo_arr[1]);
                $image_name   = time().'.jpg';
                $image_path   = SITE_PATH.'/data/upload/';
                if (!is_dir($image_path)) {
                    mkdir($image_path,0777,true);
                }
                if(file_put_contents($image_path.$image_name, $image_str)){
                    if(filesize($image_path.$image_name) > 5 * 1024 * 1024){
                        $this->error("5002", "文件过大");
                    }
                    $uploadRet = ImageV2::upload($image_path.$image_name, 'vrlive');

                    if ($uploadRet['httpcode'] == 200) {
                        //删除本地图片
                        unlink($image_path.$image_name);
                        $image_url = $uploadRet['data']['downloadUrl'];
                    } else {
                        //上传失败，返回错误
                        $this->error("上传失败");
                    }
                }
            }else{
                $image_url = $cover_img;
            }
//            if(!$_FILES['imageFile']['name']) $this->error('请上传员工照片');
//
//            if($_FILES['imageFile']['name']){
//                $news_model = new NewsModel();  //上传封面图
//                $image_url = $news_model->uploadImage();
//            }

            $people_data = array(
                'name' => I('people_name', '', 'trim'),
                'cover_image' => $image_url ? $image_url : '',
                'email' => I('email', '', 'trim'),
                'id_card' => I('id_card', '', 'trim'),
                'company_id' => I('company_id', '', 'intval') ? I('company_id', '', 'intval') : 1,
                'create_time' => time(),
            );

            $ret = $this->people_model->add($people_data);
            if($ret){
                $this->success('添加成功', U('PeopleManagement/index', array('company_id'=>I('company_id', 0, 'intval'))));
            }else{
                $this->error('添加失败，请稍后再试');
            }
            exit();
        }

        //设定ID等于一的信息是总公司信息
        $head_company = $this->company_model->where(array('id'=>$this->head_company_id))->find();
        $area_all_company = $this->company_model->where(array('status'=>1, 'city'=>$head_company['city']))->select();

        $this->assign('head_company', $head_company);
        $this->assign('area_all_company', $area_all_company);

//        $this->assign('company_id', I('company_id', 0, 'intval'));

        $this->display();
    }

    public function editPeople(){
        $people_id = I('people_id', 0, 'intval');

        if(IS_POST){
            if(!I('people_name', 0, 'trim')) $this->error('请填写员工姓名');
            if(!I('email', 0, 'trim')) $this->error('请填写员工邮箱');
            if(!I('id_card', 0, 'trim')) $this->error('请填写身份证号');
            $photo = I("photo");
            $cover_img = I("cover");
            if(!trim($photo) && !$cover_img){
                $this->error('请上传员工照片');
            }
            if(trim($photo)){
                $photo_arr = explode(',', $photo);
                $image_str 	  = base64_decode($photo_arr[1]);
                $image_name   = time().'.jpg';
                $image_path   = SITE_PATH.'/data/upload/';
                if (!is_dir($image_path)) {
                    mkdir($image_path,0777,true);
                }
                if(file_put_contents($image_path.$image_name, $image_str)){
                    if(filesize($image_path.$image_name) > 5 * 1024 * 1024){
                        $this->error("5002", "文件过大");
                    }
                    $uploadRet = ImageV2::upload($image_path.$image_name, 'vrlive');

                    if ($uploadRet['httpcode'] == 200) {
                        //删除本地图片
                        unlink($image_path.$image_name);
                        $image_url = $uploadRet['data']['downloadUrl'];
                    } else {
                        //上传失败，返回错误
                        $this->error("上传失败");
                    }
                }
            }else{
                $image_url = $cover_img;
            }
//            if(!$_FILES['imageFile']['name'] && !I('cover_image', '', 'trim')) $this->error('请上传员工照片');
//
//            if($_FILES['imageFile']['name']){
//                $news_model = new NewsModel();  //上传封面图
//                $image_url = $news_model->uploadImage();
//            }

            $save_data = array(
                'name' => I('people_name', '', 'trim'),
                'cover_image' => $image_url ? $image_url : I('cover_image', '', 'trim'),
                'email' => I('email', '', 'trim'),
                'id_card' => I('id_card', '', 'trim'),
                'company_id' => I('company_id', '', 'intval') ? I('company_id', '', 'intval') : 1,
            );

            $ret = $this->people_model->where(array('personnel_id'=>$people_id))->save($save_data);
            if($ret){
                $this->success('修改成功', U('PeopleManagement/index', array('company_id'=>I('get.company_id', 0, 'intval'))));
            }else{
                $this->error($this->people_model->getError());
            }
            exit();
        }

        $people_info = $this->people_model->alias('p')->field('p.*, c.prov, c.city, c.name as company_name')->join('LEFT JOIN vrnews1.company c ON p.company_id=c.company_id')->where(array('p.personnel_id'=>$people_id))->find();
        $city_all_company = $this->company_model->where(array('city'=>$people_info['city']))->select();

        $this->assign('people_info', $people_info);
        $this->assign('city_all_company', $city_all_company);
        $this->display();
    }

    public function delPeople(){
        if(IS_POST){
            $people_id = I('peopel_id', 0, 'intval');
            $ret = $this->people_model->where(array('personnel_id'=>$people_id))->delete();

            if($ret){
                exit(json_encode(array('code'=>200)));
            }else{
                exit(json_encode(array('code'=>171, 'msg'=>'删除失败')));
            }
        }
    }

    public function getCompanyList(){
        $city = I('city', '', 'trim');
        if(!$city) $this->ajaxReturn(array('code'=>100, 'msg'=>'参数错误'));
        $company_list = $this->company_model->where(array('city'=>$city, 'status'=>$this->status))->select();
        $this->ajaxReturn($company_list);
    }
}